/*
 * ================================================================================变量定义区
 */
var showCount = 10; //定义每页显示条数
var currentPage = 1;//全局变量，当前页
var type=0;         //没有加入到这个组织机构
var usernames = new Array(); //定义已选择的用户名数组
/*
 * ================================================================================页面初始化函数
 */
$(function()
{
	
	//初始化列表，取第一页数据
	getDataList(currentPage);

	//加载部门树
	departmentTree();
	/**
	 * 回车键绑定事件
	 */
	document.onkeydown=function(event)
	{
	    var e = event || window.event || arguments.callee.caller.arguments[0];
	               
	     if(e && e.keyCode==13)
	     { // enter 键
	         
	    	 // 调用分页查询用户，每次查询默认显示第一页
	    	 currentPage = 1;
		 	 getDataList( currentPage );
	     }
	};
}
);

/*
 * ================================================================================函数定义区
 * 
 */

/**
 * 获取列表数据
 * @param currentPage 请求的页码
 */
function getDataList(pageIndex)
{
	
	// 如果查询框中有内容
	var userNameCondition 	= $.trim($("#userNameCondition").val());
	var deptIdCondition 	= $.trim($("#dept_id").val());
	var params = window.dialogArguments;
	var deptId = params[0].id;
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/departmentManagement/queryAllUsers.do',
        dataType:"json",
        data:
        {
        	"showCount"							:	showCount,
        	"currentPage"						:	pageIndex,
        	"deptId"							:	deptId,
        	"userNameCon"						:	userNameCondition,
        	"type"								:   type,
        	"deptIdCondition"					:   deptIdCondition,
        	"query_condition_field_list"		:   "deptId,userNameCon,type,deptIdCondition"
        },
        cache:false,
        success:function(data,textStatus)
        {
        	var html = "";        	
        	var vpageData = data;
        	var totalResult = vpageData.queryParam.totalResult;
        	if(vpageData.queryResult != null)
        	{
        		//解析data, 组装成html
	        	$.each(vpageData.queryResult,function(i,n)
	        	{
	        		/*html +='<tr onclick="chooseRow(this,true);"  id="tr_index_'+i+'">';*/
	        		html +='<tr ondblclick="createSpan(this);"   id="tr_index_'+i+'">';
	        		html += '<td title='+ switcHtml(n.username) +'><input type="hidden" name="hd_userName" value="'+ switcHtml(n.username) +'"/>'+ switcHtml(n.username) +'</td>';
	        		if( n.dept_name == null || n.dept_name == "") 
	        		{
		        		html += '<td></td>';
	        		} 
	        		else 
	        		{
		        		html += '<td title='+ switcHtml(n.dept_name) +'>'+ switcHtml(n.dept_name) +'</td>';
	        		}
	        		html += '<td title='+ switcHtml(n.cn_name) +'>'+ switcHtml(n.cn_name) +'</td>';
	        		html += '<td title='+ switcHtml(n.emp_code) +'>'+ switcHtml(n.emp_code) +'</td>';
	        		html += '<td title='+ switcHtml(n.create_user) +'>'+ switcHtml(n.create_user) +'</td>';
	        		html += '<td style="text-align:center;" title='+ n.create_time +'>'+ n.create_time +'</td></tr>';
	        	}
	        	);  
        	} 
        	else
        	{
        		html = '<tr><td colspan="2">No items.</td></tr>';
        	}
        	
        	$('#tBodyList').html(html);
        	currentPage = pageIndex;
        		if(totalResult == 0)
        		{
        			$('#tBodyList').html('<tr><td style="text-align:center;">No items.</td></tr>');
        			
        			// 没有记录的时候，隐藏分页插件
        			$("#pagination").hide();
        		} 
        		else 
        		{
        			// 创建分页
        			$("#pagination").show();
        			
        			// 创建分页
        			$("#pagination").pagination(totalResult, 
        			{
        				num_edge_entries: 1, //边缘页数
        				num_display_entries: 3, //主体页数
        				current_page:currentPage,
        				callback: getDataList,
        				items_per_page:showCount //每页显示1项
        			}
        			);
        		};
        },
		error:function(e)
		{
			 openAlert("加载数据错误！"); return;
		}
	}
	);
} 

/**
 * 查询按钮事件
 */
function queryData()
{
	chooseIds = new Array();
	
	//每次查询默认显示第一页
	currentPage = 1;
	getDataList( currentPage );
}

/**
 * 选择按钮事件
 */
function choose()
{
	if( usernames.length > 0)
	{
		 var userNames = new Array();
		 for( var i = 0; i < usernames.length; i++ )
		 {
			 var userName = usernames[i];
			 userNames.push( encodeURIComponent(userName) );
		 }
	
		 var params = window.dialogArguments;
		 var deptId = params[0].id;
		 // 调用后台插入方法，进行用户的插入操作
		 openConfirm("确认添加此用户吗？",null, function()
				 {
			 
					$.ajax(
					{
						type: 'POST',
						url :  "addUserForDepartment.do?deptId=" + deptId + "&userNames=" + encodeURIComponent(userNames),
						dataType:"json",
						data:
						{
						},
						success : function(data) 
						{
							if(data == 'success')
							{
								openAlert('保存用户成功',function()
								{		
									window.close();
									$("#" + deptId).trigger("click");
								});
							}
							else
							{
								 openAlert('保存失败');
							}
						},
					});
					
				  });
	}
	else {
		openAlert("请选择一个用户！");
	}
	
}

/**
 * 取消按钮事件
 */
function cancel()
{
	 window.close();
}
 
/**
 * 动态创建span
 */ 
function createSpan(o)
{  
var id = $(o).attr("id"); 
var $usernameTd = $("#"+id).find("td:first");
var $cnnameTd = $("#"+id).find("td:eq(2)");
var username = $usernameTd.text();   
var cnname = $cnnameTd.text();  
	    if(usernames.length==0){
	    	usernames.push(username);
	    	chooseIds.push(id);
	    }else{
		    for(var i=0;i<usernames.length;i++){
		    	if(usernames[i] == username){
		    		return;
		    	}
	       } 
		    usernames.push(username);
		    chooseIds.push(id);
	    } 
	  
	var spanTag = document.createElement("span"); 
    spanTag.className = "dynamicSpan";    
    spanTag.innerHTML = cnname + " / " + username + " ";  
    var oImg = document.createElement('img');   
    oImg.src = "../res/img/item_delete.jpg";    
	
	
    oImg.onclick=
    function(){   
    	for(var i=0;i<usernames.length;i++){
	    	if(usernames[i]==username){ 
		    	   usernames.splice(i,1);
		    	   chooseIds = deleteArrayByIndex(i,chooseIds);
		    	}
    	} 
    	document.getElementById('selected').removeChild(spanTag);  
    };
    spanTag.appendChild(oImg);     
    spanTag.ondblclick=
	function(){   
    	for(var i=0;i<usernames.length;i++){
	    	if(usernames[i]==username){ 
		    	   usernames.splice(i,1);
		    	   chooseIds = deleteArrayByIndex(i,chooseIds);
		    	}
    	} 
    	document.getElementById('selected').removeChild(spanTag);   
    };
    document.getElementById('selected').appendChild(spanTag); 
}



/**
 * 显示树
 */
function showMenu() 
{
	
	var cityObj = $("#dept_name");
	var cityOffset = $("#dept_name").offset();
	$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top 
		+ cityObj.outerHeight() + "px"}).slideDown("fast");
	$("body").bind("mousedown", onBodyDown);
	
}

/**
 * 隐藏树
 */
function hideMenu() 
{
	
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
	
}

/**
 * 判断是否隐藏树
 * @param event 事件源
 */
function onBodyDown(event)
{
	
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" 
		|| $(event.target).parents("#menuContent").length>0)) 
	{
		hideMenu();
	}
	
}


/**
 * 加载树和树的点击事件
 */
function departmentTree()
{
	
	var setting = 
	{
			view: 
			{
				dblClickExpand: false
			},
			
			data: 
			{
				
				key: 
				{
					title:"titleTip"
				},
				
				simpleData: 
				{
					enable: true
				}
			},
			
			callback:
			{
				
				onClick: treeOnClick
			}
		};

	var zNodes = '[';
	
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/userManagement/queryDepts.do',
        dataType:"json",
        data:
        {
        	
        },
        
        success:function(data,textStatus)
        {
        	
        	for( var i = 0; i < data.length; i++ )
        	{
        		zNodes += '{id:"' + convertSpecialChar(data[i].deptId) + '",';
        		zNodes += 'pId:"' + convertSpecialChar(data[i].parentId) + '",';
        		zNodes += 'name:"' + convertSpecialChar( data[i].deptName ) + '",';
        		zNodes += 'titleTip:"' + convertSpecialChar( data[i].deptName ) + '",';
        		
        		if( data[i].deptDesc == null )
        		{
            		zNodes += 'deptDesc:"",';
        		} 
        		else 
        		{
            		zNodes += 'deptDesc:"' + convertSpecialChar( data[i].deptDesc ) + '",';
        		}
        		zNodes += 'isLeaf:"' + data[i].isLeaf + '",';
        		zNodes += 'open:true}';
        		
        		if( i != (data.length - 1) )
        		{
        			zNodes += ',';
        		}
        	}
        	zNodes += ']';
    		// 加载树
    		$.fn.zTree.init($("#departmentTree"), setting, eval(zNodes));
    	//hideMenu();
        },
        
		error:function(e)
		{
			openAlert("加载数据错误！"); 
			return;
		}
	});
	
}

/**
 * 树单击事件
 * @param e js的event对象
 * @param treeId 树id
 * @param treeNode 树节点对象
 */
function treeOnClick(e, treeId, treeNode) 
{
	var zTree = $.fn.zTree.getZTreeObj("departmentTree"),
		nodes = zTree.getSelectedNodes(),
		v = "",
		id = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	
	for (var i=0, l=nodes.length; i<l; i++) 
	{
		v += nodes[i].name + ",";
		id += nodes[i].id + ",";
	}
	
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	
	if (id.length >0 ) id = id.substring(0,id.length-1);
	
	var cityObj = $("#dept_name");
	cityObj.attr("value", v);
	$("#dept_id").val(id);	
	hideMenu();
	
}